<?php
/**
 * This page handles the 'projectView'
 * projectView is the display page for a project. Showing things like description, contributors, links, ratings etc etc. Found at /tool/([a-zA-Z0-9_]+)
 * 
 * This page can only be accessed using mod_rewrite.
 */

    require_once('../SiteIncludes.GLOBAL.php');
    
    if(EclipseMDE::runningOnMod_Rewrite() === false) {
	// Security Guard, Do Not Let This be accessed by any other means than mod_rewrite
	$gVAR['e'] = '404';
	require_once('error_handler.php');
    }
    
    
    $TemplateEngine->add_postloadScript('<script type="text/javascript" src="/js/ajaxConfirmer.js"></script>');
    try {
	if(isset($gVAR['alias'])) {
	    $Project =& $ProjectStash->stash($gVAR['alias']);
	    $TemplateEngine->setTitle($Project->getName());
	    $Project->instanciate();
	    
	    // Add the twitter link if it exists
	    if($Project->hasTwitter()) {
		$TemplateEngine->create_sidebar_html(
		    $Templater->createSidebarItem('Twitter Feed', $Templater->maketwitterFeed($Project->getTwitterToDisplay()))
		);
	    } else {
                $TemplateEngine->setHasSidebar(false);
                $TemplateEngine->setCentralContentFullWidth(true);
            }
	    
	    // Create the top unit
	    $TemplateEngine->create_content_html(
		    $Templater->makeprojectunit(
			    $Project->getName(), 
			    $Project->getIconURL(),
			    $Project->getDescription(), 
			    $Templater->makeleadmaintainerbox($Project->getLeadMaintainer(), $Project->getNoneLeaderMaintainers())
		    )
	    );
	    
	    
	    // ----------- Created and Edited On ------------ //
	    $creation_date = date("d/m/Y", $Project->getCreationTime());
	    $lastedit_date = date("d/m/Y - H:i:s", $Project->getLastEditTime());
	    $timeandupdate_html = <<<EOTU
		<div class="row-fluid">
		    <div class="span2" style="text-align: right;"><b>Created on&nbsp;:</b></div>
		    <div class="span4">
			{$creation_date}
		    </div>
		<!--</div>
		<div class="row-fluid">-->
		    <div class="span2" style="text-align: right;"><b>Last Updated&nbsp;:</b></div>
		    <div class="span4">
			{$lastedit_date}
		    </div>
		</div>
EOTU;
	    $TemplateEngine->create_content_html($timeandupdate_html);
	    
	    
	    // Create the tag listings
	    $tags = $Project->getTags();
	    $tBlocks = "";
	    if(count($tags) === 0) {
		$tBlocks = "There are no tags associated with this tool.";
	    } else {
		$i = 0;
		foreach($tags as $key => $value) {
		    $TagInfo =& $TagStash->get($value);
		    $tBlocks .= '&nbsp;<span style="background-color: #EEE"><a href="'.$TagInfo->getURL().'">'.$TagInfo->getName().'</a></span>';
		    
		    // Add a comma to all but last to make it a little neater
		    if(($i+1) < count($tags)) {
			$tBlocks .= ', ';
		    }
		    $i++;
		}
	    }
	    
	    
	    $tags_html = <<<EOT
		<div class="row-fluid">
		    <div class="span2" style="text-align: right;"><b>Tools Tags&nbsp;:</b></div>
		    <div class="span10">
			{$tBlocks}
		    </div>
		</div>
EOT;
	    $TemplateEngine->create_content_html($tags_html);
	    
	    
	    
	    // ------- Content Generation for lower block divs ----------- //
	    
	    
	    // -------------- Left Hand Div ------------ //
	    // ------ Website Listing ------ //
	    $websites = $Project->getWebsites();
	    $blogs = $Project->getBlogs();
	    if((count($websites)+count($blogs)) === 0) {
		$webs_html = "<i>No links given.</i><br />";
	    } else {
		$webs_html = "";
	    }
	    foreach($websites as $key => $value) {
		$webs_html .= 'Site: <a href="'.$value.'">'.$value.'</a><br />';
	    }
	    foreach($blogs as $key => $value) {
		$webs_html .= 'Blog: <a href="'.$value.'">'.$value.'</a><br />';
	    }
	    
	    // ------ Documentation Listing ----- //
	    $docs = $Project->getDoclinks();
	    if(count($docs) === 0) {
		$docs_html = "<i>No links given.</i><br />";
	    } else {
		$docs_html = "";
	    }
	    foreach($docs as $key => $value) {
		$docs_html .= '<a href="'.$value.'">'.$value.'</a><br />';
	    }
	    
	    
	    // -------------- Center-Left Div ------------ //
	    $numberOfRatings = $Project->getNumberOfRatings();
	    $averageRating = $Project->getAverageRating();
	    $ratingImage = $Templater->getRatingImage($averageRating);
	    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false) {
		if($Project->hasUserRated($_LOGGEDINUSER->get_userid())) {
		    $ratingButton = '<i>You have already rated this tool</i>';
		} else {
		    $ratingButton = $Templater->AJAX_ratingButton($Project->getAlias());
		}
	    } else {
		$ratingButton = "<i>Please login to rate</i>";
	    }
	    // Add handler for the buttons JS
	    $TemplateEngine->add_preloadScript('<script type="text/javascript" src="/js/ratingButton.js"></script>');
	    $rating_html = <<<EORHTML
		<span style="font-weight: bold;">User Rating</span><br />
		{$ratingImage}<br />
		{$ratingButton}
EORHTML;
	    
	    // -------------- Center-Right Div ----------- //
	    $depd_req = $Project->getDepdReq();
	    $depd_rec = $Project->getDepdRec();
	    if(count($depd_req) === 0) {
		$depd_req_html = "<i>No Requirements</i>";
	    } else {
		$depd_req_html = "";
		foreach($depd_req as $key => $array) {
		    $depd_req_html .= $Templater->makedependencyrow(true, $array);
		}
	    }
	    if(count($depd_rec) === 0) {
		$depd_rec_html = "<i>No Recommended Requirements</i>";
	    } else {
		$depd_rec_html = "";
		foreach($depd_rec as $key => $array) {
		    $depd_rec_html .= $Templater->makedependencyrow(true, $array);
		}
	    }
	    
	    // -------------- Right Hand Div -------------- //
	    $maintainers = $Project->getNoneLeaderMaintainers();
	    if(count($maintainers) === 0) {
		$mnts_html = "<div style=\"width: 100%; text-align: center;\"><i>-</i></div><br />";
	    } else {
		$mnts_html = "";
	    }
	    foreach($maintainers as $key => $value) {
		$mnts_user = $UserStash->get($value);
		/** Gave up with this and fell back on tables. Vertical-align would not work.
		 * <!-- <div class="row">
			<div class="span4">
			    <img src="{$mnts_user->get_profile_icon()}" style="width: 40px; height: 40px;" alt="{$mnts_user->get_username()}" />
			</div>
			<div class="span8" style="height: 40px;">
			    {$mnts_user->get_username()}
			</div>
		    </div>--> 
		 */
		$mnts_html .= <<<EOM
			<tr>
			    <td style="width: 34%;">
				<a href="{$mnts_user->get_profile_url()}">
				    <img src="{$mnts_user->get_profile_icon()}" style="width: 40px; height: 40px; border: 0px solid none;" alt="{$mnts_user->get_username()}" />
				</a>
			    </td>
			    <td style="width: 66%; vertical-align: middle; text-align: center;">
				<a href="{$mnts_user->get_profile_url()}">{$mnts_user->get_username()}</a>
			    </td>
			</tr>
EOM;
	    }
	    
	    // Creation of the units below the hero unit //
	    $social_link_href = $_ECLIPSEMDE['BASE_URL'].EclipseMDE::aliasLink($Project->getAlias());
	    $bot_html = <<<EPO
		<div class="row-fluid">
		    <div class="span3">
			<h2 style="text-align: center;">Links</h2>
			<p>
			    <!--<hr />-->
			    <b>Website(s) & Blog(s)</b><br />
				{$webs_html}
			    <br />
			    <b>Documentation</b><br />
				{$docs_html}
			</p>
		    </div>
		    <div class="span3">
			<h2 style="text-align: center;">Recommend</h2>
			<p style="text-align: center;">
			    <div class="fb-like" data-href="{$social_link_href}" data-send="false" data-width="120" data-show-faces="false" data-action="like"></div>
			    <div class="g-plusone" data-size="tall" data-annotation="inline" data-width="120" data-href="{$social_link_href}"></div>
			    <br />
				<div style="text-align: center; width: 100%;">
				    {$rating_html}
				</div>
			</p>
		    </div>
		    <div class="span3">
			<h2 style="text-align: center;">Dependencies</h2>
			<p>
			    <b>Requirements:</b><br />
				{$depd_req_html}
			    <br />
			    <b>Recommended:</b><br />
				{$depd_rec_html}
			</p>
		    </div>
		    <div class="span3">
			<h2 style="text-align: center;">Contributors</h2>
			<p><table style="display: block;">
			    {$mnts_html}
			    </table>
			</p>
		    </div>
		</div>
EPO;
	    $TemplateEngine->create_content_html($bot_html);
	    
	    // --------------- HTML For RSS Aggregation ----------------- //
	    /*$SimplePieA = new SimplePieAggregator(
		array(
		    'http://feeds.feedburner.com/eclipse/fnews?format=xml',
		    'http://feeds.feedburner.com/EclipseMarketplace?format=xml'
		    )
	    );
	    $SimplePieA->aggregate();
	    $items =& array_splice($SimplePieA->get_items(), 0, 10);
	    foreach($items as $key => $value) {
		echo '<a href="'.$value->get_link().'">'.$value->get_title().'</a><br />(<i>'.$value->get_date().'</i>)<br /><br />';
	    }*/
	    $announcements_title = "Tool Newsfeed";
	    $announcements_url = "#";
	    $announcements_feed_items = array();
	    require_simplepie();
	    $SimplePieA = new SimplePieAggregator($Project->getRSSfeeds());
	    $SimplePieA->aggregate();
	    $items =& array_splice($SimplePieA->get_items(), 0, 2);
	    foreach($items as $key => $value) {
		$date = $value->get_date();
		$title = $value->get_title();
		$url = $value->get_permalink();
		$description = $value->get_description();
		$icon = ('/img/rss_large.png');
		$announcements_feed_items[] = $Templater->makecontentfeeditem($date, $title, $url, $description, $icon);
	    }
	    $rss_url = $_ECLIPSEMDE['BASE_URL'].'/tool/'.$Project->getAlias().'/newsfeed.rss';
	    if(count($items) === 0) {
		$rss_html = '<a href="'.$rss_url.'"><img src="/img/rss2.gif" style="width: 20px; height: 15px;" alt="RSS Feed" /></a>';
		$TemplateEngine->create_content_html($Templater->maincontent_feed($announcements_title, $announcements_url, $announcements_feed_items, $rss_html));
		$TemplateEngine->create_content_html('<center><i>No news items to display for this tool</i>.</center>');
	    } else {
		$rss_html = '(<a href="'.$_ECLIPSEMDE['BASE_URL'].'/tool/'.$Project->getAlias().'/newsfeed">More</a>) <a href="'.$rss_url.'"><img src="/img/rss2.gif" style="width: 16px; height: 16px;" alt="RSS Feed" /></a>';
		$TemplateEngine->create_content_html($Templater->maincontent_feed($announcements_title, $announcements_url, $announcements_feed_items, $rss_html));
		//$TemplateEngine->create_content_html('<center></center>');
	    }
	    
	    
	    $TemplateEngine->create_content_html('<hr />');
	    // Create Edit Link if the person has permissions
	    if(isset($_LOGGEDINUSER) === true && $_LOGGEDINUSER !== false) {
		if($Project->userCanEdit($_LOGGEDINUSER->get_userid(), false)) {
		    $TemplateEngine->create_content_html(
			$Templater->makeEditDiv('This project is maintained by you.', '/edit/', $Project->getAlias())
		    );
		}
		if($_LOGGEDINUSER->get_priv_adm() === true) {
		    $TemplateEngine->create_content_html(
			$Templater->makeEditDiv('APanel::Administrate this Project.', '/admin/project/', $Project->getAlias())
		    );
		}
		
	    }
	} else {
	    throw new InvalidProjectException();
	}
    } catch(InvalidProjectException $e) {
	// Error Page for no project
	$gVAR['e'] = '404';
	require_once('error_handler.php');
    }
    
    
    
    //$TemplateEngine->create_content_html($Templater->maincontent_feed($announcements_title, $announcements_url, $announcements_feed_items));
    
    
    
    $TemplateEngine->render();
?>